package cn.zkrt.iotms.config;

import cn.hutool.core.util.RandomUtil;
import com.github.tocrhz.mqtt.autoconfigure.MqttConfigurer;
import com.github.tocrhz.mqtt.properties.ConnectionProperties;
import com.github.tocrhz.mqtt.publisher.MqttPublisher;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class MqttConfig extends MqttConfigurer {

    @Value("${mqtt.broker}")
    private String broker;

    @Value("${mqtt.clientId}")
    private String clientId;

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    @Bean
    public MqttClient mqttClient() throws MqttException {

        MemoryPersistence persistence = new MemoryPersistence();

        MqttClient mqttClient = new MqttClient(broker, clientId, persistence);

        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setUserName(username);
        connOpts.setPassword(password.toCharArray());
        connOpts.setCleanSession(true);
        mqttClient.connect(connOpts);

        return mqttClient;
    }


    @Bean
    public MqttPublisher mqttPublisher() {
        return new MqttPublisher();
    }


    @Override
    public void beforeCreate(ClientRegistry registry) {
//        System.out.println("whDeviceTopic:===================================" +"================================================================"+whDeviceTopic);
        registry.clear();
        String defaultClientId = clientId + "-" + RandomUtil.randomNumbers(9);
        ConnectionProperties properties = new ConnectionProperties();
        properties.setUri(new String[]{broker});
        properties.setUsername(username);
        properties.setPassword(password);
        properties.setClientId(defaultClientId);
        properties.setCleanSession(true);
        properties.setConnectionTimeout(10);
        properties.setKeepAliveInterval(20);
        properties.setEnableSharedSubscription(true);
//        properties.setWill("willTopic",WILL_DATA,2,FALSE);
        registry.add(defaultClientId, properties);
    }




}

